package com.easemob.easeui.ui;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.cloudcc.cloudframe.CApplication;
import com.cloudcc.mobile.R;
import com.easemob.EMConnectionListener;
import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.easeui.widget.EaseConversationList;
import com.easemob.easeui.widget.EaseTitleBar;
import com.litesuits.android.log.Log;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;

import static com.cloudcc.cloudframe.CApplication.isfirstyunxin;

/**
 * 云信消息列表fragment 基类
 *
 */
public class EaseConversationListFragment extends EaseBaseFragment {
	protected EditText query;
	protected ImageButton clearSearch;
	protected boolean hidden;
	protected List<EMConversation> conversationList = new ArrayList<EMConversation>();
	protected EaseConversationList conversationListView;
	protected TextView btnSelectPerson;
	protected FrameLayout errorItemContainer;
	protected TextView sousuo_hint;
	protected boolean isConflict;
	protected TextView pop_location;
	protected FrameLayout message_null;
	private RelativeLayout yunxinxiaoxiyindao;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.ease_fragment_conversation_list,
				container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if (savedInstanceState != null
				&& savedInstanceState.getBoolean("isConflict", false))
			return;
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	protected void initView() {
		inputMethodManager = (InputMethodManager) getActivity()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		// 会话列表控件
		conversationListView = (EaseConversationList) getView().findViewById(
				R.id.list);
		btnSelectPerson = (TextView) getView().findViewById(
				R.id.btnSelectPerson);
		// 搜索框
		query = (EditText) getView().findViewById(R.id.query);
		//hint
		sousuo_hint = (TextView) getView().findViewById(R.id.sousuo_hint);
		pop_location = (TextView) getView().findViewById(R.id.pop_location);
		// 搜索框中清除button
		clearSearch = (ImageButton) getView().findViewById(R.id.search_clear);
		errorItemContainer = (FrameLayout) getView().findViewById(
				R.id.fl_error_item);

		titleBar = (EaseTitleBar) getView().findViewById(R.id.title_bar);
		message_null = (FrameLayout) getView().findViewById(R.id.message_null_x);
		yunxinxiaoxiyindao = (RelativeLayout)getView().findViewById(R.id.yunxinyindao);
		if(CApplication.isfirstyunxin){
			yunxinxiaoxiyindao.setVisibility(View.VISIBLE);
		}else{
			yunxinxiaoxiyindao.setVisibility(View.GONE);
		}
		yunxinxiaoxiyindao.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				yunxinxiaoxiyindao.setVisibility(View.GONE);
				CApplication.isfirstyunxin = false;
			}
		});
	}

	@Override
	protected void setUpView() {
		conversationList.addAll(loadConversationList());

        conversationListView.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);

		conversationListView.setMenuCreator(creator);

		conversationListView.init(conversationList);

		if (listItemClickListener != null) {
			conversationListView
					.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							EMConversation conversation = conversationListView
									.getItem(position);
							listItemClickListener
									.onListItemClicked(conversation);
						}
					});
		}

		EMChatManager.getInstance().addConnectionListener(connectionListener);

		query.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				conversationListView.filter(s);
				if (s.length() > 0) {
					clearSearch.setVisibility(View.VISIBLE);
					sousuo_hint.setVisibility(View.INVISIBLE);
				} else {
					clearSearch.setVisibility(View.INVISIBLE);
					sousuo_hint.setVisibility(View.VISIBLE);
				}
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void afterTextChanged(Editable s) {
			}
		});
		clearSearch.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				query.getText().clear();
				hideSoftKeyboard();
			}
		});

		conversationListView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				hideSoftKeyboard();
				return false;
			}
		});
		titleBar.setLeftLayoutClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getActivity().finish();
			}
		});
	}

	protected EMConnectionListener connectionListener = new EMConnectionListener() {

		@Override
		public void onDisconnected(int error) {
			if (error == EMError.USER_REMOVED
					|| error == EMError.CONNECTION_CONFLICT) {
				isConflict = true;
			} else {
				handler.sendEmptyMessage(0);
			}
		}

		@Override
		public void onConnected() {
			handler.sendEmptyMessage(1);
		}
	};
	private EaseConversationListItemClickListener listItemClickListener;

	protected Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				onConnectionDisconnected();
				break;
			case 1:
				onConnectionConnected();
				break;

			default:
				break;
			}
		}
	};
	public EaseTitleBar titleBar;

	/**
	 * 连接到服务器
	 */
	protected void onConnectionConnected() {
		errorItemContainer.setVisibility(View.GONE);
	}

	/**
	 * 连接断开
	 */
	protected void onConnectionDisconnected() {
		errorItemContainer.setVisibility(View.VISIBLE);
	}

	/**
	 * 刷新页面
	 */
	public void refresh() {
		conversationList.clear();
		conversationList.addAll(loadConversationList());
		conversationListView.refresh();
	}

	/**
	 * 获取会话列表
	 * 
	 * @param context
	 * @return +
	 */
	protected List<EMConversation> loadConversationList() {
		// 获取所有会话，包括陌生人
		Hashtable<String, EMConversation> conversations = EMChatManager
				.getInstance().getAllConversations();
		if(conversations.size() == 0) {
			message_null.setVisibility(View.VISIBLE);
		}else {
			message_null.setVisibility(View.INVISIBLE);

		}
		// 过滤掉messages size为0的conversation
		/**
		 * 如果在排序过程中有新消息收到，lastMsgTime会发生变化 影响排序过程，Collection.sort会产生异常
		 * 保证Conversation在Sort过程中最后一条消息的时间不变 避免并发问题
		 */

		List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
		synchronized (conversations) {
			for (EMConversation conversation : conversations.values()) {
				if (conversation.getAllMessages().size() != 0) {
					// if(conversation.getType() !=
					// EMConversationType.ChatRoom){
					sortList.add(new Pair<Long, EMConversation>(conversation
							.getLastMessage().getMsgTime(), conversation));
					// }
					Log.d("huanxin", conversation
							.getLastMessage().getUserName());
				}
			}
		}
		try {
			// Internal is TimSort algorithm, has bug
			sortConversationByLastChatTime(sortList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<EMConversation> list = new ArrayList<EMConversation>();
		for (Pair<Long, EMConversation> sortItem : sortList) {
			list.add(sortItem.second);
		}
		for (int i = 0; i < list.size(); i++) {
			list.get(i).getUserName();
			list.get(i).getAllMessages();
			Log.d("huanxin", list.get(i).getUserName()+"::"+list.get(i).getAllMessages());
		}
		return list;
	}

	/**
	 * 根据最后一条消息的时间排序
	 * 
	 * @param usernames
	 */
	private void sortConversationByLastChatTime(
			List<Pair<Long, EMConversation>> conversationList) {
		Collections.sort(conversationList,
				new Comparator<Pair<Long, EMConversation>>() {
					@Override
					public int compare(final Pair<Long, EMConversation> con1,
							final Pair<Long, EMConversation> con2) {

						if (con1.first == con2.first) {
							return 0;
						} else if (con2.first > con1.first) {
							return 1;
						} else {
							return -1;
						}
					}

				});
	}

	protected void hideSoftKeyboard() {
		if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (getActivity().getCurrentFocus() != null)
				inputMethodManager.hideSoftInputFromWindow(getActivity()
						.getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		this.hidden = hidden;
		if (!hidden && !isConflict) {
			refresh();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		if (!hidden) {
			refresh();
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		EMChatManager.getInstance()
				.removeConnectionListener(connectionListener);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (isConflict) {
			outState.putBoolean("isConflict", true);
		}
	}

	public interface EaseConversationListItemClickListener {
		/**
		 * 会话listview item点击事件
		 * 
		 * @param conversation
		 *            被点击item所对应的会话
		 */
		void onListItemClicked(EMConversation conversation);
	}

	/**
	 * 设置listview item点击事件
	 * 
	 * @param listItemClickListener
	 */
	public void setConversationListItemClickListener(
			EaseConversationListItemClickListener listItemClickListener) {
		this.listItemClickListener = listItemClickListener;
	}
	SwipeMenuCreator creator = new SwipeMenuCreator() {

		@Override
		public void create(SwipeMenu menu) {
//			// create "open" item
//			SwipeMenuItem openItem = new SwipeMenuItem(
//                    getActivity().getApplicationContext());
//			// set item background
//			openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
//					0xCE)));
//			// set item width
//			openItem.setWidth(dp2pxx(0));
//			// set item title
//			openItem.setTitle("1");
//			// set item title fontsize
//			openItem.setTitleSize(18);
//			// set item title font color
//			openItem.setTitleColor(Color.WHITE);
//			// add to menu
//			menu.addMenuItem(openItem);

			// create "delete" item
			SwipeMenuItem deleteItem = new SwipeMenuItem(
                    getActivity().getApplicationContext());
			// set item background
			deleteItem.setBackground(new ColorDrawable(Color.rgb(0xE4, 0x35,
					0x20)));
			// set item width
			deleteItem.setWidth(dp2pxx(86));
			// set a icon
			deleteItem.setIcon(R.drawable.delete_slidelist);
			// add to menu
			menu.addMenuItem(deleteItem);
		}
	};
    public int dp2pxx(float dipValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }
}
